import 'dart:io';

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_member/model/StudentSignIn.dart';
import 'package:flutter_member/widget/calendarshow/flutter_clean_calendar.dart';
import 'package:flutter_member/widget/custom_appbar.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:toast/toast.dart';
///学生信息
class StudentInfoPage extends StatefulWidget {
  @override
  _StudentInfoPageState createState() => _StudentInfoPageState();
}

const String MIN_DATETIME = '2019-05-17';
const String MAX_DATETIME = '2020-12-31';

class _StudentInfoPageState extends State<StudentInfoPage> {
  //全局 Key 用来获取 Form 表单组件
  GlobalKey<FormState> updateKey = GlobalKey<FormState>();

  //初始化賦值
  var userObjectId = '';
  var objectId = '';
  var _userName = TextEditingController();
  DateTime _brt = DateTime.now();
  var _newValue = 'f';
  var _address = TextEditingController();
  var _phone = TextEditingController();

//  暱稱輸入
  final TextEditingController _nickController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  var testName;
  var src = '';
  var logoState = '';

  ///学生信息
  var student = ParseObject("Student");

  @override
  void initState() {
    super.initState();
    _getStuInfo();
  }

  /// 查詢學生信息
  Future<void> _getStuInfo() async {
    final ParseUser user = await ParseUser.currentUser();
    var query = QueryBuilder(ParseObject("Member"))
      ..whereEqualTo("objectId", user.get("member")['objectId'])
      ..includeObject(['student']);
    var repStuInfo = await query.query();
    if (repStuInfo.success && repStuInfo.results != null) {
      if(repStuInfo.results.first["student"]!=null){
        repStuInfo.results.map((e) => setState(() => student = e["student"])).toList();
      }else{
        Toast.show("你还没有添加学生", context,gravity: Toast.CENTER);
        Navigator.pop(context);
      }
    } else {
      Toast.show("你还不是会员", context,gravity: Toast.CENTER);
      Navigator.pop(context);
    }
  }

  //修改用戶信息
  Future<void> _updateUser(String name, String phone, String address,
      String gander, DateTime brt) async {
    var updateForm = updateKey.currentState;
    //验证 Form表单
    if (updateForm.validate()) {
      updateForm.save();
      var member = ParseObject('Member');
      member
        ..set('objectId', objectId)
        ..set('phone', phone)
        ..set('addressArea', address)
        ..set('birthday', brt)
        ..set('gender', gander);
      var res = await member.save();

      var u = ParseObject('_User');
      u..set('objectId', userObjectId)..set('displayName', name);
      var resUser = await u.save();
      if (res.success && resUser.success) {
        Toast.show("修改成功！", context,
            duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
      } else {
        Toast.show("修改失敗，確認資料後請重試！", context,
            duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
      }
    } else {
      Toast.show("輸入有誤，請檢查後重試！", context,
          duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
    }
  }


  //更換頭像
  _updateAvatar() async {
    final ParseUser user = await ParseUser.currentUser();
    var query = QueryBuilder(ParseObject("Member"))
      ..whereEqualTo("objectId", user.get("member")["objectId"])
      ..includeObject(['student']);
    var rep = await query.query();
    if(rep.results!=null&&rep.success){
      File image = await ImagePicker.pickImage(source: ImageSource.gallery);
      ParseFile parseFile = ParseFile(image, name: "image.jpg", debug: true);

      var stu = ParseObject('Student');
      stu.set('objectId', rep.results.first["student"]["objectId"]);
      stu.set<ParseFile>("avatar", parseFile);
      var res = await stu.save();
      try {
        if (res.success) {
          print('------>保存成功');
          await _getStuInfo();
        }else{
          Toast.show("保存失敗", context,gravity: Toast.CENTER);
          print('------>保存失败');
        }
      } catch (e) {
        print(e);
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, designSize: Size(375, 667), allowFontScaling: false);
    return CustomAppBar(
      title: '編輯個人資料',
      hight: 79,
      upperColor: 0Xff4d80c5,
      lowerColor: 0xffE5EEF6,
      body: Container(
        margin: EdgeInsets.only(top: 30),
        alignment: Alignment.topCenter,
        child: EasyRefresh(
          child: Stack(
            alignment: Alignment.topCenter,
            children: [
              _contentWidget(),
              _headWidget(),
            ],
          ),
        ),
      ),
    );
  }

  ///头像
  Widget _headWidget() {
    return InkWell(
      onTap: () => _updateAvatar(),
      child: Container(
        height: 96,
        width: 96,
        child: Stack(
          children: [
            Container(
              height: 96,
              width: 96,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(96)),
                color: Colors.amberAccent,
              ),
              child: AspectRatio(
                aspectRatio: 1 / 1,
                child: student.get("avatar") != null
                    ? CircleAvatar(
                  backgroundImage: NetworkImage(student.get("avatar")["url"]),
                )
                    : CircleAvatar(
                  backgroundColor: Colors.transparent,
                  backgroundImage: AssetImage('images/avatar.png'),
                  radius: 55,
                ),
              ),
            ),
            Container(
              height: 20,
              width: 20,
              margin: EdgeInsets.only(left: 70, top: 70),
              decoration: BoxDecoration(
                  color: Colors.amberAccent,
                  borderRadius: BorderRadius.all(Radius.circular(20))),
              child: Image.asset('images/changephoto2.png'),
            ),
          ],
        ),
      ),
    );
  }

//  内容区域
  Widget _contentWidget() {
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(18)),
          boxShadow: [
            BoxShadow(
                color: Color(0xffE5EEF6), blurRadius: 10.0, spreadRadius: 5.0),
          ]),
      margin: EdgeInsets.only(top: 75),
      child: Stack(
        children: [
          Container(
            height: ScreenUtil().setHeight(114),
            width: ScreenUtil().setWidth(335),
            decoration: BoxDecoration(
                color: Color(0xffE5EEF6),
                borderRadius: BorderRadius.all(Radius.circular(24))),
          ),
          Container(
            height: ScreenUtil().setHeight(124),
            width: ScreenUtil().setWidth(335),
            margin: EdgeInsets.only(top: 8),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(24))),
            child: Column(
              children: [
                _inputWidget(
                    title: '暱稱',
                    controller: _nickController,
                    hint:
                    student != null ? student["displayName"] : "username"),
                _inputWidget(
                    title: '手機號碼', controller: _phoneController, hint: 'phone'),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _inputWidget(
      {@required String title,
        TextEditingController controller,
        String hint = 'null'}) {
    return Container(
      padding: EdgeInsets.all(15),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            flex: 3,
            child: Text(
              title,
              style: TextStyle(
                  color: Color(0xff7B7B7B),
                  fontSize: ScreenUtil().setSp(14)),
            ),
          ),
          Expanded(
            flex: 2,
            child: TextField(
              controller: controller,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: hint,
                hintStyle: TextStyle(
                  color: Color(0xff154D7C),
                  fontSize: ScreenUtil().setSp(15),
                ),
              ),
              style: TextStyle(
                color: Color(0xff154D7C),
                fontSize: ScreenUtil().setSp(15),
              ),
            ),
          )
        ],
      ),
    );
  }
}